<?php

class AdminPostController extends \BaseController {
	
	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{ 		        
		$page = Input::get('page', 1);
		
		$postModel = new Post();
		$data = $postModel->getPostByPage($page, 2);
		
		$posts = Paginator::make($data->items, $data->totalItems, 2);
		
		return View::make('admins.posts.index', compact('posts'));
	}


	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		return View::make('admins.posts.create');
	}


	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		$input = Input::all();
        $validation = Validator::make($input, Post::$rules);
        
        if ($validation->passes()) {            
            $post = new Post($input);
			$post->read_more = (strlen($post->content) > 120) ? substr($post->content, 0, 120) : $post->content;
        	$post->save();

            return Redirect::route('admin.post.index')
            	->with('message', 'Created successful.');
        }

        return Redirect::back()
            ->withInput()
            ->withErrors($validation);
	}


	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		echo 'show';
	}


	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		$post = Post::find($id);
		
        if (is_null($post)) {
            return Redirect::route('admin.post.index');
        }
        
        return View::make('admins.posts.edit', compact('post'));
	}


	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		$input = Input::all();
        $validation = Validator::make($input, Post::$rules);
        
        if ($validation->passes()) {            
            $post = Post::find($id);
            $post->title = $input['title'];
            $post->content = $input['content'];
            $post->read_more = (strlen($post->content) > 120) ? substr($post->content, 0, 120) : $post->content;
            
            // Avoiding resubmission of same content
            $message = 'Nothing to update.';
            if (count($post->getDirty()) > 0) {
            	$post->save();
            	$message = 'Updated successful.';
            }
           	
           	return Redirect::route('admin.post.index')
           		->with('message', $message);
        }
        
		return Redirect::back()
            ->withInput()
            ->withErrors($validation);
	}


	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		Post::find($id)->delete();
		
        return Redirect::route('admin.post.index')
        	->with('message', 'Deleted successful.');
	}


}
